package org.example.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.utils.Const;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(Const.ORDER_CORS)
public class CustomizeCorsFilter extends HttpFilter {
    @Value("${spring.security.customize.flow-limit.cors.methods}")
    private String allowMethods;
    @Value("${spring.security.customize.flow-limit.cors.allow-origin}")
    private String allowOrigin;

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        addCoreHeader(request, response);
        chain.doFilter(request, response);
    }

    private void addCoreHeader(HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", allowOrigin.isEmpty() ? request.getHeader("Origin") : allowOrigin);
        response.addHeader("Access-Control-Allow-Methods", allowMethods);
        response.addHeader("Access-Control-Allow-Headers", "Authorization,Content-type");
    }
}
